package mp3organizer;

import com.mpatric.mp3agic.ID3v2;
import com.mpatric.mp3agic.InvalidDataException;
import com.mpatric.mp3agic.Mp3File;
import com.mpatric.mp3agic.NotSupportedException;
import com.mpatric.mp3agic.UnsupportedTagException;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Aderthad
 */
public class ggmee {

    public static void main(String[] args) {
        try {
            final File folder = new File("e:\\Aderthad\\Music\\_k\\Hye Eunee\\1\\혜은이 - 여전히-강해야 돼\\");

            if (!folder.exists()) {
                System.out.println("The folder doesn't exist.");
                return;
            }

            final File output = new File(folder.getAbsolutePath() + File.separator + "_NEW");
            if (output.exists()) {
                if (!output.delete()) {
                    System.err.println("Couldn't delete output file.");
                    return;
                }
            }

            final Map<Path, List<Path>> albums = new HashMap<>();

            Files.walkFileTree(folder.toPath(), new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path t, BasicFileAttributes bfa) throws IOException {
                    albums.put(t, new ArrayList<Path>());

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path t, BasicFileAttributes bfa) throws IOException {
                    if (t.getFileName().toString().endsWith(".mp3")) {
                        albums.get(t.getParent()).add(t);
                    }

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path t, IOException ioe) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path t, IOException ioe) throws IOException {

                    return FileVisitResult.CONTINUE;

                }
            });

            output.mkdir();

            for (Map.Entry<Path, List<Path>> entry : albums.entrySet()) {
                String albumName = entry.getKey().getFileName().toString();

                int i = albumName.indexOf("-");
                if (i != -1) {
                    albumName = albumName.substring(i + 1).trim();
                }

                Path relativeOutput = folder.toPath().relativize(entry.getKey());
                String absoluteOutput = output + File.separator + relativeOutput.toString();

                new File(absoluteOutput).mkdirs();

                for (Path song : entry.getValue()) {
                    int in = song.getFileName().toString().indexOf("-");
                    String artist = song.getFileName().toString().substring(0, in).trim();

                    String fullPathString = song.getFileName().toString();
                    String songNameWoutext = fullPathString.substring(0, fullPathString.length() - 4);
                    String songName = songNameWoutext.toString().substring(in + 1).trim();

                    Mp3File mp3file = new Mp3File(song.toString());

                    if (!mp3file.hasId3v2Tag()) {
                        System.err.println(song.toString() + " doesn't have a tag.");
                        continue;
                    }

                    ID3v2 iD3v2Tag = mp3file.getId3v2Tag();

                    iD3v2Tag.setComment(" ");
                    iD3v2Tag.setCopyright(" ");
                    iD3v2Tag.setUrl(" ");

                    iD3v2Tag.setTitle(songName);
                    iD3v2Tag.setAlbum(albumName);
                    iD3v2Tag.setAlbumArtist(artist);
                    iD3v2Tag.setArtist(artist);

                    String track = iD3v2Tag.getTrack().trim();
                    String formattedTrack = (track == null || track.isEmpty()) ? "" : String.format("%02d", Integer.parseInt(iD3v2Tag.getTrack())) + ". ";

                    String newSongFileName = formattedTrack + songName + ".mp3";

                    mp3file.save(absoluteOutput + File.separator + newSongFileName);

                    System.out.println("Saving " + relativeOutput + File.separator + newSongFileName);
                }

            }
        } catch (IOException | UnsupportedTagException | InvalidDataException | NotSupportedException | NumberFormatException ex) {
            System.out.println(ex.getMessage());
        }

    }

}
